package com.skiving.cloud.auth.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.dao.SaTokenDaoForRedisson;
import cn.dev33.satoken.same.SaSameUtil;
import cn.dev33.satoken.solon.integration.SaTokenInterceptor;
import com.skiving.cloud.auth.constant.AuthConstant;
import com.skiving.cloud.common.utils.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.annotation.Inject;
import org.redisson.api.RedissonClient;

@Slf4j
@Configuration
public class AuthConfiguration {
    @Bean(index = -100)
    public SaTokenInterceptor saTokenInterceptor() {
        return new SaTokenInterceptor()
                // 指定 [拦截路由] 与 [放行路由]
                .addInclude("/**")
                .addExclude("/favicon.ico",
                        "/auth/login",
                        "/auth/captcha.jpg",
                        "/swagger**",
                        "/healthz**",
                        "/metrics/**")
                .setAuth(obj -> {
                    // 校验 Same-Token 身份凭证,服务间调用校验
                    String token = SaHolder.getRequest().getHeader(SaSameUtil.SAME_TOKEN);
                    SaSameUtil.checkToken(token);
                }).setError(e -> {
                    log.error(e.getMessage(), e);
                    return ReturnT.error(AuthConstant.CODE_NOT_LOGIN, e.getMessage());
                });
    }

    @Bean
    public SaTokenDao saTokenDaoInit(@Inject RedissonClient redisClient) {
        return new SaTokenDaoForRedisson(redisClient);
    }
}
